"""
KnowYou AI Backend 主应用
提供智能聊天、情感分析和语音合成功能
使用重构后的架构，提高性能和可维护性
"""

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import uvicorn
import logging
import os
from contextlib import asynccontextmanager
from dotenv import load_dotenv

# 导入核心组件
from app.core.config import settings
from app.core.http_client import get_http_client, close_http_client
from app.core.cache import cache_manager
from app.core.database import init_database, close_database

# 导入路由
from app.routers import chat, auth, image

# 导入中间件
from app.middleware.jwt_middleware import JWTMiddleware

# 加载环境变量
load_dotenv()


def setup_logging():
    """
    配置日志系统
    设置合适的日志级别和格式
    """
    # 确保日志目录存在
    os.makedirs("logs", exist_ok=True)

    # 创建格式化器
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )

    # 配置根日志器
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)

    # 清除现有处理器
    root_logger.handlers.clear()

    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)

    # 文件处理器（只记录错误）
    from logging.handlers import RotatingFileHandler

    file_handler = RotatingFileHandler(
        "logs/error.log",
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=5,
        encoding="utf-8",
    )
    file_handler.setLevel(logging.ERROR)
    file_handler.setFormatter(formatter)
    root_logger.addHandler(file_handler)

    # 设置特定日志器级别
    logging.getLogger("uvicorn").setLevel(logging.WARNING)
    logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
    logging.getLogger("httpx").setLevel(logging.WARNING)

    # 关闭SQLAlchemy和数据库相关的详细日志
    logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
    logging.getLogger("sqlalchemy.dialects").setLevel(logging.WARNING)
    logging.getLogger("sqlalchemy.pool").setLevel(logging.WARNING)
    logging.getLogger("sqlalchemy.orm").setLevel(logging.WARNING)
    logging.getLogger("aiomysql").setLevel(logging.WARNING)
    logging.getLogger("pymysql").setLevel(logging.WARNING)
    logging.getLogger("aiomysql.pool").setLevel(logging.WARNING)
    logging.getLogger("aiomysql.connection").setLevel(logging.WARNING)

    # 应用日志保持INFO级别
    logging.getLogger("app").setLevel(logging.INFO)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用生命周期管理
    处理启动和关闭时的资源管理
    """
    logger = logging.getLogger("app.main")

    # 启动时执行
    logger.info("🚀 KnowYou AI Backend 启动中...")

    try:
        # 初始化缓存管理器
        if settings.redis_url and settings.redis_url != "redis://localhost:6379":
            await cache_manager.init_redis(settings.redis_url)
            logger.info("✅ 缓存管理器初始化完成")
        else:
            logger.info("⚠️ 使用内存缓存（Redis未配置）")

        # 初始化HTTP客户端
        client = get_http_client()
        logger.info("✅ HTTP客户端初始化完成")

        # 初始化数据库
        if init_database():
            logger.info("✅ 数据库已就绪")
        else:
            logger.warning("⚠️ 数据库初始化失败")

        # 设置应用状态
        app.state.settings = settings
        app.state.cache_manager = cache_manager

        logger.info(f"🎉 应用启动完成！监听端口:8000")

        yield

    except Exception as e:
        logger.error(f"❌ 应用启动失败: {e}")
        raise
    finally:
        # 关闭时执行
        logger.info("🔄 KnowYou AI Backend 关闭中...")

        try:
            # 关闭HTTP客户端
            await close_http_client()
            logger.info("✅ HTTP客户端已关闭")

            # 关闭缓存连接
            await cache_manager.close()
            logger.info("✅ 缓存连接已关闭")

            # 关闭数据库连接
            await close_database()
            logger.info("✅ 数据库连接已关闭")

        except Exception as e:
            logger.error(f"❌ 关闭资源时出错: {e}")

        logger.info("👋 应用已完全关闭")


def create_app() -> FastAPI:
    """
    创建FastAPI应用实例
    配置中间件和路由

    Returns:
        FastAPI: 配置好的应用实例
    """
    # 设置日志
    setup_logging()

    # 创建应用实例
    app = FastAPI(
        title="KnowYou AI Backend",
        description="智能聊天API，支持多模态交互和情感分析",
        version="1.0.0",
        lifespan=lifespan,
        docs_url="/docs" if settings.debug else None,
        redoc_url="/redoc" if settings.debug else None,
    )

    # 配置不需要JWT验证的路径
    jwt_exclude_paths = [
        "/docs",
        "/redoc",
        "/openapi.json",
        "/static/*",
        "/",
        "/auth/verify",  # 验证令牌接口
        "/chat/test-sse",  # 测试SSE接口
    ]

    # 添加JWT验证中间件
    app.add_middleware(JWTMiddleware, excluded_paths=jwt_exclude_paths)

    # 配置CORS
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # 生产环境应限制为特定域名
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
        expose_headers=["*"],
    )

    # 挂载静态文件（如果目录存在）
    static_dir = "static"
    if os.path.exists(static_dir):
        app.mount("/static", StaticFiles(directory=static_dir), name="static")
    else:
        # 创建静态文件目录
        os.makedirs(static_dir, exist_ok=True)
        app.mount("/static", StaticFiles(directory=static_dir), name="static")

    # 包含路由
    app.include_router(chat.router)
    app.include_router(auth.router)
    app.include_router(image.router)

    # 根路径
    @app.get("/")
    async def root():
        return {
            "message": "KnowYou AI Backend API",
            "version": "1.0.0",
            "status": "running",
        }

    # 健康检查接口
    @app.get("/health")
    async def health_check():
        return {
            "status": "healthy",
            "version": "1.0.0",
            "services": {
                "http_client": "active",
                "cache": "active" if cache_manager.is_redis_connected else "memory",
            },
        }

    return app


# 创建应用实例
app = create_app()


if __name__ == "__main__":
    """
    主入口点
    启动开发服务器
    """
    logger = logging.getLogger("app.main")

    try:
        # 启动服务器
        host = settings.host
        port = settings.port

        logger.info(f"🌟 启动开发服务器: http://{host}:{port}")
        logger.info(f"📚 API文档: http://{host}:{port}/docs")

        uvicorn.run(
            "main:app",
            host=host,
            port=port,
            reload=settings.debug,
            log_level="info" if settings.debug else "warning",
        )

    except KeyboardInterrupt:
        logger.info("🛑 服务器被用户中断")
    except Exception as e:
        logger.error(f"❌ 服务器启动失败: {e}", exc_info=True)
